﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Timers;

namespace Pg.BioMedics.SDR.Diagnostics
{    
    /// <summary>
    /// Provides functionalit of avg counter for simple number of items
    /// </summary>
    public class AverageNumberOfItemsPerformanceCounter : BasePerformanceCounter
    {
        #region Constants

        private const int TimerInterval = 1000;

        #endregion

        #region Fields

        private IList<long> samples = new List<long>();
        private Timer timer;

        #endregion

        #region Constructors and destructors

        internal AverageNumberOfItemsPerformanceCounter(string category, string name)
            : base(category, name, PerformanceCounterType.NumberOfItems64) 
        {
            this.timer = new Timer(1000) { Enabled = false };
            this.timer.Elapsed += new ElapsedEventHandler(OnTimerElapsed);
        }       

        #endregion

        #region Event handlers

        /// <summary>
        /// Event jandler for timer elapsed event. This event is intended to 
        /// be executed on avg value calculation request.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnTimerElapsed(object sender, ElapsedEventArgs e)
        {
            lock (this.timer)
            {
                // disable timer on calculation time
                this.timer.Enabled = false;

                // calculate and apply avg value
                Apply((long)this.samples.Average());
                this.samples.Clear();
            }
        }

        #endregion

        #region Methods

        /// <summary>
        /// Sets simple sample value
        /// </summary>
        /// <param name="value">Counter sample</param>
        public void Set(long value)
        {
            lock (this.timer)
            {
                if (!this.timer.Enabled)
                    this.timer.Enabled = true;

                this.samples.Add(value);
            }
        }

        #endregion
    }
}
